//
//  CollectionDataManager.m
//  collection
//
//  Created by 靖 张 on 11/22/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "CollectionDataManager.h"
#import "TagInfo.h"
#import "MentionedMessage.h"
#import "PrivateLetterItem.h"
#import "Utility.h"
#import "UserInfo.h"

@interface CollectionDataManager()

@property (nonatomic, retain)   NSMutableArray* availableFeedList;
@property (nonatomic, retain)   NSMutableDictionary* tagFeeds;

- (BOOL)loadLatestInfo;
- (BOOL)loadHotTag;
- (BOOL)loadPrivateLetter;
- (BOOL)loadMentionedMsg;

- (BOOL)loadCacheData;
- (BOOL)loadLoginUser;
- (BOOL)loadSearchHistory;
- (BOOL)loadTagFeedList;

@end


@implementation CollectionDataManager

@synthesize feedList = _feedList;
@synthesize hotTagList = _hotTagList;
@synthesize privateLetterSet = _privateLetterSet;
@synthesize mentionedMsgList = _mentionedMsgList;
@synthesize cachedUsers = _cachedUsers;
@synthesize currentLoginUser = _currentLoginUser;
@synthesize searchHistory = _searchHistory;

@synthesize availableFeedList = _availableFeedList;
@synthesize tagFeeds = _tagFeeds;

static CollectionDataManager* sharedDataManager = nil;

+ (id)sharedInstance {
    @synchronized(self) {
        if (sharedDataManager == nil) {
            sharedDataManager = [[CollectionDataManager alloc] init];
            [sharedDataManager loadFromLocalStorage];
        }
        
        return sharedDataManager;
    }
}

+ (void)destroyInstance {
    @synchronized(self) {
        if (sharedDataManager != nil) {
            [sharedDataManager release];
        }
    }
}

- (void)dealloc {
    
    [_feedList release];
    [_hotTagList release];
    [_mentionedMsgList release];
    [_privateLetterSet release];
    
    self.cachedUsers = nil;
    self.searchHistory = nil;
    self.availableFeedList = nil;
    self.tagFeeds = nil;
    
    [super dealloc];
}

- (BOOL)updateFromServer {
    
    return YES;
}

- (BOOL)loadFromLocalStorage {
    
    // Cache
    [self loadCacheData];
    
    // Feed list
    [self loadLatestInfo];
    
    // Hot tag
    [self loadHotTag];
    
    // Mentioned message
    [self loadMentionedMsg];
    
    // Private letters
    [self loadPrivateLetter];
    
    // Login user
    [self loadLoginUser];
    
    // Search history
    [self loadSearchHistory];
    
    // Tag feed list
    [self loadTagFeedList];
    
    return YES;
}

- (BOOL)saveToLocalStorage {
    
    return YES;
}

#pragma mark - Private methods

- (BOOL)loadLatestInfo {
    
    NSMutableArray* feeds = [NSMutableArray array];
    
    Feed* newFeed = nil;
    
    // First feed
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10001;
    newFeed.feedType        = FeedType_Original;
    newFeed.userID          = 1;
    newFeed.nickname        = @"CollectionMVP";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_1"];
    newFeed.text            = @"蔡康永的个人收藏展将于2012年2月24日在今日美术馆举行";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-06-05 22:20:12"];
    newFeed.tags            = [NSArray arrayWithObjects:@"字画", @"清代木质藏品", nil];
    newFeed.picturesURL     = [NSArray arrayWithObjects:@"abc", @"bcd", @"cde", nil];
    newFeed.pictures        = [NSArray arrayWithObjects:@"pic_1", @"pic_4", @"pic_2", @"pic_3", nil];
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 12;
    newFeed.forwardNum      = 100;
    newFeed.originalFeed    = nil;
    
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Second feed
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10002;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 2;
    newFeed.nickname        = @"梦回大唐";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_2"];
    newFeed.text            = @"有人同去吗？";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-06-05 20:01:00"];;
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = [feeds objectAtIndex:0];
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Three feed
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10003;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 3;
    newFeed.nickname        = @"收藏爱好者";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_3"];
    newFeed.text            = @"好期待啊，那么多珍贵的展品:)";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-06-01 11:23:45"];;
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = [feeds objectAtIndex:0];
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Four
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10004;
    newFeed.feedType        = FeedType_Original;
    newFeed.userID          = 4;
    newFeed.nickname        = @"小兵张嘎";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_4"];
    newFeed.text            = @"地坛的收藏品展览开始了，希望能淘到喜欢的藏品。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-05-30 09:20:12"];
    newFeed.tags            = [NSArray arrayWithObjects:@"青花瓷", @"玉器", nil];
    newFeed.picturesURL     = [NSArray arrayWithObjects:@"abc", @"bcd", @"cde", @"def", nil];
    newFeed.pictures        = [NSArray arrayWithObjects:@"pic_5", @"pic_6", @"pic_7", @"pic_8", nil];
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = nil;
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Five
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10005;
    newFeed.feedType        = FeedType_Original;
    newFeed.userID          = 5;
    newFeed.nickname        = @"资深收藏家";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_5"];
    newFeed.text            = @"本人收藏艺术品二十年，希望广交朋友，共同交流收藏爱好。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-05-21 07:33:15"];
    newFeed.tags            = [NSArray arrayWithObjects:@"青花瓷", @"清代木质藏品", nil];
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = nil;
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Six
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10006;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 3;
    newFeed.nickname        = @"收藏爱好者";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_3"];
    newFeed.text            = @"老兄，明儿咱们一起去吧～";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-05-20 12:20:12"];
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = [feeds objectAtIndex:3];
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Seven
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10007;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 3;
    newFeed.nickname        = @"收藏爱好者";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_3"];
    newFeed.text            = @"您已经有二十年收藏经验了啊，肯定有很多珍贵的藏品和收藏心得吧，希望有机会向您请教啊。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-05-18 02:20:12"];;
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = [feeds objectAtIndex:4];
    [feeds addObject:newFeed];
    [newFeed release];
    
    // Eight
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10008;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 1;
    newFeed.nickname        = @"CollectionMVP";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_1"];
    newFeed.text            = @"向您学习了，有空给我们分享一下经验和心得吧，呵呵。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-05-10 17:20:12"];
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = [feeds objectAtIndex:4];
    [feeds addObject:newFeed];
    [newFeed release];
    
    self.feedList = [NSMutableArray arrayWithArray:feeds];
    
    NSMutableArray* availableFeeds = [NSMutableArray array];
    // 9
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10009;
    newFeed.feedType        = FeedType_Original;
    newFeed.userID          = 1;
    newFeed.nickname        = @"CollectionMVP";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_1"];
    newFeed.text            = @"最新比较烦，比较烦，比较烦，我看那前方怎么也看不到岸。。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-04-21 12:20:12"];
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = nil;
    [availableFeeds addObject:newFeed];
    [newFeed release];
    
    // 10
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10010;
    newFeed.feedType        = FeedType_Original;
    newFeed.userID          = 3;
    newFeed.nickname        = @"收藏爱好者";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_3"];
    newFeed.text            = @"我准备近期办一个有关收藏品的展览，请问大家有什么感兴趣的吗，我可以提前准备一下。到时多多交流哈。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-03-06 12:00:12"];
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = nil;
    [availableFeeds addObject:newFeed];
    
    // 11
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10011;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 3;
    newFeed.nickname        = @"收藏爱好者";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_3"];
    newFeed.text            = @"怎么没有人关注呢，呜呜～";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-02-16 09:20:12"];
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = [availableFeeds objectAtIndex:1];
    [availableFeeds addObject:newFeed];
    [newFeed release];
    
    // 12
    newFeed = [[Feed alloc] init];
    newFeed.feedID          = 10012;
    newFeed.feedType        = FeedType_Comment;
    newFeed.userID          = 3;
    newFeed.nickname        = @"收藏爱好者";
    newFeed.avatarURL       = @"http://url";
    newFeed.avatar          = [UIImage imageNamed:@"User_3"];
    newFeed.text            = @"我准备近期办一个有关收藏品的展览，请问大家有什么感兴趣的吗，我可以提前准备一下。到时多多交流哈。";
    newFeed.publishTime     = [Utility convertStrToDate:@"2012-01-23 12:20:12"];;
    newFeed.tags            = nil;
    newFeed.picturesURL     = nil;
    newFeed.pictures        = nil;
    newFeed.favorNum        = 0;
    newFeed.commentNum      = 0;
    newFeed.forwardNum      = 0;
    newFeed.originalFeed    = nil;
    [availableFeeds addObject:newFeed];
    [newFeed release];
    
    self.availableFeedList = availableFeeds;
    
    return YES;
}

- (BOOL)loadHotTag {
    
    NSString* tmp[] = {@"青花瓷", @"黄花梨", @"清代木质", @"铅笔", @"陶瓷", @"明代家具", @"玉器", @"青铜", @"瓷器", @"珠宝", @"古玩", @"收藏动态"};
    int tmp1[] = {10, 20, 30, 20, 15, 20, 20, 20, 20, 30, 30, 5};
    int tmp2[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    
    NSMutableArray* hotList = [NSMutableArray array];
    for (int i = 0; i < sizeof(tmp2) / sizeof(int); i++) {
        TagInfo* tag = [[TagInfo alloc] init];
        tag.name    = tmp[i];
        tag.weight  = tmp1[i];
        tag.index   = tmp2[i];
        
        [hotList addObject:tag];
        [tag release];
    }
    
    _hotTagList = [[NSArray alloc] initWithArray:hotList];
    
    return YES;
}

- (BOOL)loadMentionedMsg {
    
    NSMutableArray* mentionedMsgList = [NSMutableArray array];
    
    for (UserInfo* user in self.cachedUsers) {
        MentionedMessage* msg = [[MentionedMessage alloc] init];
        msg.userID      = user.userID;
        msg.userName    = user.nickname;
        msg.avatar      = user.avatar;
        msg.avatarURL   = @"abcdefg";
        msg.timestamp   = [NSDate date];
        
        [mentionedMsgList addObject:msg];
        [msg release];
    }
    
    _mentionedMsgList = [[NSArray alloc] initWithArray:mentionedMsgList];
    
    return YES;
}

- (BOOL)loadPrivateLetter {
    
    NSString* textPattern[] = {
        @"国家电视台在赛后点评说，AC米兰在比赛的前45分钟并不怎么活跃，是诺切里诺的进球帮米兰走出了困境，只是博阿滕赢得的点球非常的可疑。",
        @"AC米兰(微博)2-0攻下防守坚韧的锡耶纳，除了需要感谢诺切里诺的首开纪录之外，在两个进球中，罗比尼奥的作用也不可忽视。",
        @"加利亚尼曾用“跑得多的人，得到的就多”来形容过诺切里诺，事实也是如此",
        @"谈到不断进球的诺切里诺，阿莱格里满意的说道：“诺切里诺？我希望他本赛季能打进15球，目前他已经打进了6球，已经证明了自己是一个配得上AC米兰的球员。”",
        @"当然，AC米兰也是有恃无恐，目前球队锋线拥有伊布、罗比尼奥、帕托，就算特维斯不来，留下因扎吉，这4个人再加上马克西-洛佩斯，也算是豪华配置了"
    };
    
    NSMutableDictionary* letterGroup = [[NSMutableDictionary alloc] init];
    
    // Three users' data
    for (long long userID = 1ll; userID <= 3ll; userID++) {
        NSMutableArray* threads = [[NSMutableArray alloc] init]; 
        for (long long activeUserID = 1ll; activeUserID <= 5ll; activeUserID++) {
            if (activeUserID == userID) {
                continue;
            }
            
            NSMutableArray* letterList = [[NSMutableArray alloc] init];
            for (int i = 0; i < 5; i++) {
                PrivateLetterItem* item = [[PrivateLetterItem alloc] init];
                if ((i % 2) == 0) {
                    item.senderID = userID;
                    item.receiverID = activeUserID;
                }
                else {
                    item.senderID = activeUserID;
                    item.receiverID = userID;
                }
                
                item.text = textPattern[i];
                item.publishTime = [NSDate date];
                
                [letterList addObject:item];
                [item release];
            }
            
            PrivateLetterThread* newThread = [[PrivateLetterThread alloc] init];
            newThread.userID        = userID;
            newThread.objectID      = activeUserID;
            newThread.objectAvatarURL   = @"abcdefg";
            newThread.letterList    = letterList;
            [letterList release];
            [threads addObject:newThread];
            [newThread release];
        }
        
        [letterGroup setValue:threads forKey:[NSString stringWithFormat:@"%lld", userID]];
        [threads release];
    }
    
    _privateLetterSet = letterGroup;
    
    return YES;
}

- (NSArray*)commentListOfFeed:(id)feed {
    
    NSMutableArray* comments = [NSMutableArray array];
    
    int feedCount = [self.feedList count];
    for (int i = feedCount - 1; i >= 0; i--) {
        Feed* feedItem = [self.feedList objectAtIndex:i];
        if (feedItem.originalFeed == feed) {
            [comments addObject:feedItem];
        }
    }
    
    return comments; 
}

- (BOOL)loadCacheData {
    
    // Cached User
    self.cachedUsers = [NSMutableSet set];
    
    UserInfo* user = nil;
    user = [[UserInfo alloc] init];
    user.userID = 1;
    user.avatar = [UIImage imageNamed:@"User_1"];
    user.nickname = @"CollectionMVP";
    user.signature  = @"关注瓷器动态，关注有价值的收藏器，热衷收藏交流，广交天下朋友，唐代，宋代，元代，明代，清代，各种瓷器，都是最爱";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 2;
    user.avatar = [UIImage imageNamed:@"User_2"];
    user.nickname   = @"梦回大唐";
    user.signature = @"谁知道最新出土的汉代玉器在哪里展出吗？很感兴趣，想去一见";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 3;
    user.avatar = [UIImage imageNamed:@"User_3"];
    user.nickname   = @"收藏爱好者";
    user.signature = @"专业古董收藏爱好者";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 4;
    user.avatar = [UIImage imageNamed:@"User_4"];
    user.nickname   = @"小兵张嘎";
    user.signature = @"我是新手，大家多多指导:)";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 5;
    user.avatar = [UIImage imageNamed:@"User_5"];
    user.nickname   = @"资深收藏家";
    user.signature = @"收藏是对生活品质的追求";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 6;
    user.avatar = [UIImage imageNamed:@"User_3"];
    user.nickname = @"如日中天";
    user.signature = @"我站在山顶，感受那一阵阵吹来的轻风";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 7;
    user.avatar = [UIImage imageNamed:@"User_4"];
    user.nickname = @"林小伟";
    user.signature = @"轻轻的我走了，正如我轻轻地来，我轻轻地招手，作别那西天的云彩";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 8;
    user.avatar = [UIImage imageNamed:@"User_5"];
    user.nickname = @"小浣熊";
    user.signature = @"那就这样吧";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 9;
    user.avatar = [UIImage imageNamed:@"User_2"];
    user.nickname = @"钢铁侠";
    user.signature = @"钢铁侠，蜘蛛侠，蝙蝠侠，绿灯侠，机器侠，还有啥？";
    [self.cachedUsers addObject:user];
    [user release];
    
    user = [[UserInfo alloc] init];
    user.userID = 10;
    user.avatar = [UIImage imageNamed:@"User_1"];
    user.nickname = @"最美的音符";
    user.signature = @"每一个音符，都像是那欢呼雀跃的生命";
    [self.cachedUsers addObject:user];
    [user release];

    return YES;
}

- (BOOL)loadTagFeedList {
    
    NSMutableDictionary* tagFeedsDictionary = [[NSMutableDictionary alloc] init];
    self.tagFeeds = tagFeedsDictionary;
    [tagFeedsDictionary release];
    
    for (Feed* feed in self.feedList) {
        if (feed.feedType != FeedType_Original) {
            continue;
        }
        
        if (feed.tags != nil && feed.tags.count > 0) {
            for (NSString* tag in feed.tags) {
                NSMutableArray* feedListWithTag = [self.tagFeeds objectForKey:tag];
                if (feedListWithTag == nil) {
                    feedListWithTag = [[NSMutableArray alloc] init];
                    [self.tagFeeds setObject:feedListWithTag forKey:tag];
                    [feedListWithTag release];
                }
                
                [feedListWithTag addObject:feed];
            }
        }
    }
    
    return YES;
}

- (UserInfo*)cacheUserByUserID:(long long)userID {
    
    for (UserInfo* user in self.cachedUsers) {
        if (user.userID == userID) {
            return user;
        }
    }
    
    return nil;
}

- (BOOL)loadLoginUser {
    
    self.currentLoginUser = [self cacheUserByUserID:1];
    
    return YES;
}

- (BOOL)loadSearchHistory {
    
    self.searchHistory = [NSMutableArray arrayWithObjects:nil];
    
    return YES;
}

- (NSArray*)getMoreFeed:(NSDate *)lastFeedTime requestNum:(int)num {

    NSMutableArray* newFeedList = [[[NSMutableArray alloc] init] autorelease];
    for (int i = 0; (i < num) && (i < self.availableFeedList.count); i++) {
        Feed* feed = [self.availableFeedList objectAtIndex:0];
        [newFeedList addObject:feed];
        [self.feedList addObject:feed]; 
        [self.availableFeedList removeObject:feed];
    }
    
    return newFeedList;
}

- (BOOL)addFeed:(Feed *)feed {
    
    if (![self.feedList containsObject:feed]) {
        [self.feedList insertObject:feed atIndex:0];
    }
    
    return YES;
}

- (NSArray*)feedListWithTag:(NSString *)tag {
    
    return [self.tagFeeds objectForKey:tag];
}

@end
